const enterpriseVue = new Vue({
  el: '#app',
  data() {
    //校验身份证号
    var checkIDCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('身份证号不能为空'));
      }
      setTimeout(() => {
        if (!ID_Validity(value)) {
          callback(new Error('请输入正确的身份证号'));
        }
      }, 100);
    }
    return {
      pickerOptions: pickerOptions,
      rules: {
        ID_Number: [{
          validator: checkIDCard,
          trigger: 'blur'
        }]
      },
      form: {
        Member_Rights_SerialNumber: '',  //主键
        Member_Rights_Name: '',   //权益名称
        Prepayment: '',   //最低预付款
        Discount: '',   //折扣价
        Picture_URL: '',
        pic: '',
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Children: {
          member_rights_appid: [{
            Member_Rights_ApplD_SerialNumber: '',
            Member_Rights_SerialNumber: '',
            App_ID: '',   //小程序ID
          }]
        }

      },
      dialogImageUrl: '',
      dialogVisible: false,
      shop: [],
      loading: false
    }
  },
  mounted() {
    const Member_Rights_SerialNumber = sessionStorage.getItem("Member_Rights_SerialNumber")
    this.getAppID()
    this.getData(Member_Rights_SerialNumber)
  },
  methods: {
    getData(Member_Rights_SerialNumber) {
      const _this = this
      $.ajax({
        //	url: '../getContractContentByContract_SerialNumberAction',
        url: DomainName + '/getMemberRightsEditAction',
        type: 'POST',
        data: { Data: Member_Rights_SerialNumber, token: $.cookie("token") },
        success: function (res) {
          _this.form = res.member_rights_info[0]
          console.log(_this.form)
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    // 获取小程序
    getAppID() {
      let _this = this
      $.ajax({
        url: DomainName + '/getInquiryAction',
        type: 'POST',
        data: {
          Data: 'enterprise_appid',
          token: $.cookie("token"),
          Enterprise_Info_SerialNumber: $.cookie("enterprise")
        },
        success: function (res) {
          console.log(res)
          _this.shop = res
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    //权益头像
    uploadFront(file) {
      let _this = this
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        num = 0.4
      } else if (file.size > 500000) {
        num = 0.2
      }
      new Compressor(file, {
        quality: num,
        // if(file.size) {
        // }
        success(file) {
          console.log(file.size)
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                _this.form.pic = e.target.result
                if (Result.Status == "success") {
                  _this.form.Picture_URL = Result.Picture_Url
                  _this.$message.success('上传成功')
                  console.log(Result.Picture_Url);
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    //查看图片
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file
    },
    // 删除图片
    handleRemove() {
      this.form.Picture_URL = ''
    },
    // 增加小程序
    add_member_rights_appid() {
      this.form.Children.member_rights_appid.push({
        Member_Rights_ApplD_SerialNumber: '',
        Member_Rights_SerialNumber: '',
        App_ID: '',   //小程序ID
      })
    },
    remove_member_rights_appid() {
      if (this.form.Children.member_rights_appid.length > 1) {
        this.form.Children.member_rights_appid.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    submitForm(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { add, modify } = _this.deal()
          let data = {}
          if (add == null) {
            data = { Data: JSON.stringify({ Modify: { member_rights_info: [modify] } }), token: $.cookie("token") }
          } else {
            data = {
              Data: JSON.stringify(
                {
                  Modify: { member_rights_info: [modify] },
                  Add: { member_rights_info: [add] }
                }
              ),
              token: $.cookie("token")
            }
          }
          _this.loading = true
          $.ajax({
            url: DomainName + '/getEditAction',
            type: 'POST',
            data: data,
            success: function (res) {
              console.log('提交结果', res)
              if (res.Status === 'success') {
                _this.$message.success("提交成功")
                window.location.href = './MemberBenefits.html'

              } else {
                _this.$message.error("提交失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    deal() {
      const add = deepClone(this.form)
      const modify = deepClone(this.form)
      let add_member_rights_appid = [], modify_member_rights_appid = []
      for (const i in modify.Children.member_rights_appid) {
        const obj = modify.Children.member_rights_appid[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_member_rights_appid.push(obj)
        } else {
          modify_member_rights_appid.push(obj)
        }
      }

      add.Children.member_rights_appid = add_member_rights_appid

      modify.Children.member_rights_appid = modify_member_rights_appid

      if (add_member_rights_appid.length == 0) {
        return { add: null, modify };
      }
      return { add, modify };
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  }
})